#include "mytcpserver.h"
#include "command.h"
#include "cstring"
#include "cstdio"
MyTcpServer::MyTcpServer(QObject *parent) :
    QObject(parent)
{
    server = new QTcpServer(this);
    // whenever a user connects, it will emit signal
    connect(server, SIGNAL(newConnection()),this, SLOT(newConnection()));

    if(!server->listen(QHostAddress::Any, 38990))
        qDebug() << "Server could not start";
    else
        qDebug() << "Server started!";
    count=0;

    db.setHostName("23.95.31.58");
    db.setDatabaseName("testdb");       //这里输入你的数据库名
    db.setUserName("root");
    db.setPassword("1");
    qDebug()<<db.open();

}


void MyTcpServer::newConnection()
{
    // need to grab the socket
    qDebug()<<"incoming connection";
    QTcpSocket *socket =server->nextPendingConnection();
    char* buf=new char[500];
    connect(socket, SIGNAL(readyRead()), this, SLOT(readMessage()));
    // socket->close();
    delete[] buf;
}


void MyTcpServer::readMessage()
{

    qDebug()<<"\nread start";
    Command command;
    QTcpSocket *socket= dynamic_cast<QTcpSocket *> ( this->sender());
    //int len=socket->read((char*)(command.rawdata),1024);
    QString sql_qurey;
    QByteArray b=socket->readAll();
    //socket->waitForReadyRead();
    // qDebug()<<b;

    data_print((UCHAR*)b.data(),b.length());
    int len=b.length();
    // GPS device raw data 2 array
    memcpy(command.rawdata,b.data(),b.length());
    qDebug()<<"length="<<len;
    //  data_print((UCHAR*)b.data(),b.length());
    command.resolve_from_rawdata();

    int fun_code= command.fun_code;
    qDebug()<<"fun code"<<command.fun_code;
    qDebug()<<"count"<<command.count;

    if(FUN_CODE_REGISTER==fun_code)
    {
        command.register_sync_time();

    }
    if(FUN_DEVICE_RETUEN_TIME==fun_code  )
    {
        command.configure(count);  //do sth here

    }
    if(FUN_RETURN_CONFIGURE==fun_code)
    {
        //if it is return configure
        //report 2 database, the confiure is done

        command.finish_configure_database();
        command.configure(count);

    }

    //gps data frame from device
    if(FUN_DATA_UPLOAD==fun_code)
    {

        command.return_status();
        //write to database

    }
    //  data_print(command.rawdata,command.frame_length);
    qDebug()<<"frame length read message"<<command.frame_length;
    //  data_print(command.rawdata,command.frame_length);
    QByteArray write_data((char*)command.rawdata,command.frame_length);
    int write_len=socket->write(write_data);
    qDebug()<<"write len"<<write_len;
    this->count++;

}


//debug function
void MyTcpServer::data_print(UCHAR* p,int length)
{
    int i=0;
    //QTextStream myout(stdout);
    qDebug()<<"print start print length="<<length;
    for(i=0;i<length;i++)
    {
        printf("%02x ",*(p+i));
    }
    // fflush(stdout);
    qDebug()<<"print end";
}
